package zxj.weixin.mp.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import zxj.weixin.mp.domain.Account;
import zxj.weixin.mp.service.AccountService;
import zxj.weixin.mp.service.MessageService;
import zxj.weixin.mp.service.WeixinService;
import zxj.weixin.mp.utils.WeixinUtils;

/**
 * 微信公众号接口Controller
 * 
 * @author zhuxuejiang
 *
 */
@RestController
@RequestMapping("/weixin")
public class CallbackController {

	private static final Logger LOGGER = LoggerFactory.getLogger(CallbackController.class);

	@Autowired
	private AccountService accountService;

	@Autowired
	private MessageService messageService;

	@Autowired
	private WeixinService weixinService;

	/**
	 * 处理GET请求，用于与微信的对接
	 * 
	 * @param appId     公众号的唯一标识
	 * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	 * @param timestamp 时间戳
	 * @param nonce     随机数
	 * @param echostr   随机字符串
	 * @return 处理结果
	 * @throws Exception
	 */
	@GetMapping("/callback")
	public String get(String appId, String signature, String timestamp, String nonce, String echostr) throws Exception {

		if (StringUtils.isBlank(appId) || StringUtils.isBlank(signature) || StringUtils.isBlank(timestamp)
				|| StringUtils.isBlank(nonce) || StringUtils.isBlank(echostr)) {
			return "";
		}

		// 查询微信公众号是否存在，如不在则不允许接入
		Account officialAccount = accountService.getByAppId(appId);
		if (null == officialAccount) {
			return "";
		}

		// 验证消息是否来自微信服务器
		if (WeixinUtils.checkSignature(officialAccount.getToken(), signature, timestamp, nonce)) {
			return echostr;
		}

		return "";
	}

	/**
	 * 处理POST请求，用于处理微信消息
	 * 
	 * @param appId   公众号的唯一标识
	 * @param request HttpRequest对象
	 * @return 处理结果
	 * @throws Exception
	 */
	@PostMapping("/callback")
	public String post(String appId, HttpServletRequest request) throws Exception {

		if (StringUtils.isBlank(appId)) {
			return "success";
		}

		// 查询微信公众号是否存在，如不在则不允许接入
		Account officialAccount = accountService.getByAppId(appId);
		if (null == officialAccount) {
			return "success";
		}

		// 处理微信消息
		String reply = messageService.processMessage(request.getInputStream());
		if (StringUtils.isBlank(reply)) {
			return "success";
		}

		return reply;
	}

	/**
	 * 获取JS_SDK wx.config配置信息
	 *
	 * @param params 参数Map
	 * @return 配置信息Map
	 * @throws Exception
	 */
	@PostMapping("/jsSdkConfig")
	public Map<String, String> getJsSdkConfig(@RequestBody Map<String, String> params) throws Exception {
		if (null == params) {
			return null;
		}

		String appId = params.get("appId");
		String url = params.get("url");

		if (StringUtils.isBlank(appId) || StringUtils.isBlank(url)) {
			LOGGER.error("获取JS_SDK wx.config配置信息错误！");
			LOGGER.error("appId=" + appId);
			LOGGER.error("url=" + url);
			return null;
		}

		String accessToken = weixinService.getAccessToken(appId);
		if (StringUtils.isBlank(accessToken)) {
			LOGGER.error("获取JS_SDK wx.config配置信息错误：accessToken is null ！");
			LOGGER.error("appId=" + appId);
			return null;
		}

		String jsapiTicket = weixinService.getJsapiTicket(appId, accessToken);
		if (StringUtils.isBlank(jsapiTicket)) {
			LOGGER.error("获取JS_SDK wx.config配置信息错误：jsapiTicket is null ！");
			LOGGER.error("appId=" + appId);
			LOGGER.error("accessToken=" + accessToken);
			return null;
		}

		return WeixinUtils.getJsSdkConfig(jsapiTicket, url);
	}

	@GetMapping("/hello")
	public String hello() throws Exception {
		return "hello";
	}

}
